package controller

import (
	"strconv"
	"web-app/logic"
	"web-app/models"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func CreatePostHandler(c *gin.Context) {
	//获取参数及参数校验
	p := new(models.Post)
	err := c.ShouldBindJSON(p)
	if err != nil {
		ResponseError(c, CodeInvalidParam)
		return
	}
	//从c取到当前请求的用户的ID值
	userid, err := GetCurrentUser(c)
	if err != nil {
		ResponseError(c, CodeNeedLogin)
		return
	}
	p.AuthorID = userid
	//创建帖子
	err = logic.CreatePost(p)
	if err != nil {
		zap.L().Error("logic.CreatePostHandler() failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
	}
	//返回相应
	ResponseSuccess(c, nil)
}

func GetPostDetailHandler(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		ResponseError(c, CodeInvalidParam)
		return
	}
	data, err := logic.GetPostDetail(id)
	if err != nil {
		zap.L().Error("logic.GetPostDetail error", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, data)
}

// func GetPostListHandler(c *gin.Context) {
// 	page, size := getPostInfo(c)
// 	data, err := logic.GetPostList(page, size)
// 	if err != nil {
// 		zap.L().Error("logic.GetPostList error", zap.Error(err))
// 		ResponseError(c, CodeServerBusy)
// 		return
// 	}
// 	ResponseSuccess(c, data)
// }

// func getPostInfo(c *gin.Context) (page int64, size int64) {
// 	a := c.Query("page")
// 	b := c.Query("size")
// 	var err error
// 	page, err = strconv.ParseInt(a, 10, 64)
// 	if err != nil {
// 		page = 1
// 	}
// 	size, err = strconv.ParseInt(b, 10, 64)
// 	if err != nil {
// 		size = 10
// 	}
// 	return
// }

// 根据时间或分数或社区ID
func GetPostListHandler2(c *gin.Context) {
	p := &models.ParamPostList{
		Page:  1,
		Size:  10,
		Order: models.OrderTime,
	}
	err := c.ShouldBindQuery(p)
	if err != nil {
		zap.L().Error("ShouldBindQuery failed", zap.Error(err))
		ResponseError(c, CodeInvalidParam)
		return
	}
	data, err := logic.GetPostListNew(p)
	if err != nil {
		zap.L().Error("logic.GetPostList failed")
		ResponseError(c, CodeServerBusy)
	}
	ResponseSuccess(c, data)
	
}

func PostVoteController(c *gin.Context) {
	//参数校验
	p := new(models.VoteData)
	err := c.ShouldBindJSON(p)
	if err != nil {
		ResponseError(c, CodeInvalidParam)
		return
	}
	userID, err := GetCurrentUser(c)
	if err != nil {
		ResponseError(c, CodeNeedLogin)
		return
	}
	err = logic.PostVote(userID, p)
	if err != nil {
		zap.L().Error("logic.PostVote failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, "sucess....")
}

